<?php
require 'JXwebAuto.php';

// emulate $_GET for CLI version
for ($i=1; $i<$argc; $i++) {
  list($k, $v) = split('=', $argv[$i]);
  $_GET[$k] = $v;
}

if ($_GET['key'] !== JXW_CORE_ADMIN_PWD) die('Key error');  

set_time_limit(0);

$ACC = new JXAccounts();
$JXWA = new JXwebAuto();

$now = time();
$minNext = $now + $JXWA->checkTime;

function autoplay(&$acc) {
  global $JXWA, $ACC;
  $JXWA->loadUser($acc);
  $JXWA->init();
  $JXWA->autoplay();
  $ACC->updateAccount($JXWA);
}

foreach ($ACC->accounts as $acc) {
  if ($acc['enabled'] && $acc['next'] < $now) {
    if (function_exists('pcntl_fork')) {
      $pid = pcntl_fork();
      if($pid == -1) {
        autoplay($acc);
      }
      else if ($pid == 0) {
        autoplay($acc);
        die;
      }  
    }
    else {
      autoplay($acc);
    }
  }

  if ($acc['enabled']) {
    echo "Account ".$acc['username']." - time: ". ($acc['next']-$now) . "<br/>\n";
    $minNext = min($minNext, $acc['next']);
  }
}

$nextTime = max($minNext - $now, 60);  // min period: 60 seconds
echo '<p>JXwebAuto runner - PHP version. Rand: '. rand(100,999) .'</p><script language="Javascript">setTimeout("window.location.reload()", '. ($nextTime+1)*1000 .');</script>';
